package com.lzh.hosp.filter;

import com.lzh.hosp.model.SysUser;
import com.lzh.hosp.service.SysUserService;
import com.lzh.hosp.service.UserDetailsServiceImpl;
import com.lzh.hosp.utils.JwtUtil;
import com.lzh.hosp.utils.RedisCache;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends BasicAuthenticationFilter {
    @Autowired
    RedisCache redisCache;

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    SysUserService sysUserService;

    public JwtAuthenticationTokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request.getRequestURI().equals("/sys/user/login")){
            chain.doFilter(request, response);
            return;
        }
        String jwt = request.getHeader("token");
        if (StringUtils.isEmpty(jwt)) {
            chain.doFilter(request, response);
            return;
        }

        Claims claim = null;
        try {
            claim = JwtUtil.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (claim == null) {
            throw new JwtException("token 异常");
        }
        if (JwtUtil.isTokenExpired(claim)) {
            throw new JwtException("token已过期");
        }

        String userid = claim.getSubject();
        // 获取用户的权限等信息
        SysUser sysUser = (SysUser)redisCache.getCacheObject("login:" + userid);
        if(Objects.isNull(sysUser)){
            throw new RuntimeException("用户未登录");
        }

        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(userid, null, userDetailsService.getUserAuthority(sysUser.getId()));

        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request, response);
    }
}
